package com.lz.library.utils

import android.app.Activity
import android.graphics.Rect
import android.view.View
import android.view.ViewTreeObserver
import androidx.activity.ComponentActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Lifecycle.State
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
import com.lz.library.extension.getStatusHeight

/**
 * author: you : 2018/11/7
 * activity中有使用EditText弹出软键盘时,需要将键盘上的界面调整时使用
 * @param rootView 滑动界面布局的根目录
 * @param scrollStatusBar 滑动调试是否包含StatusBar
 */
class ActivityScrollObserver private constructor(
    private val rootView: View,
    private val scrollStatusBar: Boolean = false
) : LifecycleEventObserver {
    /**
     * 窗体控件上一次的高度,用于监听键盘弹起
     */
    private var mLastHeight = 0

    //ViewTreeObserver
    private var listener: ViewTreeObserver.OnGlobalLayoutListener? = null

    //Window size
    private val rect by lazy { Rect() }

    override fun onStateChanged(owner: LifecycleOwner, event: Lifecycle.Event) {
        if (event == Lifecycle.Event.ON_CREATE) {
            val decorView = (owner as Activity).window.decorView
            val diff = if (scrollStatusBar) getStatusHeight() else 0
            listener = ViewTreeObserver.OnGlobalLayoutListener {
                decorView.getWindowVisibleDisplayFrame(rect)
                if (mLastHeight != rect.bottom) {
                    mLastHeight = rect.bottom
                    val params = rootView.layoutParams
                    params.height = rect.bottom - rootView.top - diff
                    rootView.layoutParams = params
                }
            }
            decorView.viewTreeObserver.addOnGlobalLayoutListener(listener)
        } else if (event == Lifecycle.Event.ON_DESTROY) {
            (owner as Activity).window.decorView.viewTreeObserver.removeOnGlobalLayoutListener(listener)
            listener = null
        }
    }

    companion object {

        fun observe(activity: ComponentActivity, rootView: View, scrollStatusBar: Boolean = true) {
            if (activity.lifecycle.currentState == State.DESTROYED) return
            activity.lifecycle.addObserver(ActivityScrollObserver(rootView, scrollStatusBar))
        }
    }
}